package com.heima.gateway.filter;

import com.heima.common.util.AppJwtUtil;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @author: itheima
 * @create: 2022-06-30 11:35
 */
@Component
public class AuthFiller implements GlobalFilter, Ordered {

    /**
     * 过滤器逻辑：从客户端请求头中token获取 用户JWT令牌，解析令牌是否合法，获取令牌中载荷中用户信息
     *
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1.获取到请求，响应对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        try {

            //2. 判断请求是否需要进行校验令牌
            String path = request.getURI().getPath();
            if (path.contains("/login")) {
                //白名单请求，登录请求直接放行
                return chain.filter(exchange);
            }
            //3.从请求对象中获取请求头
            String jwtToken = request.getHeaders().getFirst("token");
            if (StringUtils.isBlank(jwtToken)) {
                //令牌未提交 响应http状态码401
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                return response.setComplete();
            }

            //4.调用工具类进行校验
            //4.1 如果校验JWT成功，在有效期内，得到用户载荷信息
            Claims claims = AppJwtUtil.getClaimsBody(jwtToken);
            if (claims != null) {
                //4.2 从载荷中获取用户信息
                Object userId = claims.get("userId");
                Object userName = claims.get("userName");

                //4.3 将用户信息路由到其他微服务中
                request.mutate().header("userId", userId.toString());
                request.mutate().header("userName", userName.toString());
                return chain.filter(exchange);
            }
        } catch (Exception e) {
            e.printStackTrace();
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        return response.setComplete();
    }


    /**
     * 过滤器执行顺序
     *
     * @return
     */
    @Override
    public int getOrder() {
        return 0;
    }
}
